package network;

import model.*;
import java.io.*;
import java.net.*;
import java.util.StringTokenizer;
import java.util.List;
import java.util.LinkedList;
public class AcolyteServerThread extends Thread
{
  protected Socket clientSocket = null;
  protected AcolyteGameServer server;
  protected PrintWriter out;
  protected BufferedReader in;
  
  public AcolyteServerThread(AcolyteGameServer server, Socket socket) {
    super("AcolyteServerThread");
    clientSocket = socket;
    this.server = server;
  }
  
  public void run()
  {
    try
    {
      out = new PrintWriter(clientSocket.getOutputStream(), true);
      in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
      String inputLine, outputLine;
      
      while ((inputLine = in.readLine()) != null) { 
        parseCommand(inputLine);
        outputLine = inputLine;
        //out.println(outputLine);
        if (outputLine.equals("quit"))
          break;
      }
      
      out.close();
      in.close();
      clientSocket.close();
    } catch (IOException e)
    {
      //don't waste memory on this thread anymore
      System.out.println("reading failed");
      server.removeThread(this);
      //System.exit(-1);
    }
  }
  
  protected void parseCommand(String input)
  {
    StringTokenizer st = new StringTokenizer(input);
    String command = st.nextToken();
    List<String> parameters = new LinkedList<String>();
    while(st.hasMoreTokens())
    {
      parameters.add(st.nextToken());
    }
    if("broadcast".equals(command))
      server.broadcast(parameters);
    if("quit".equals(command))
      out.println("Bye.");
  }
  
  public void broadcast(List<String> message)
  {
    String display = "";
    for(String bit:message)
    {
      display += bit + ' ';
    }
    out.println(display);
  }
  
}